'''
Created on Feb 3, 2014

@author: James
'''

import random
import string
import hashlib
import logging
from google.appengine.ext import db

class UserEntry(db.Model):
    username = db.StringProperty(required=True)
    saltedPwd = db.StringProperty(required=True)
    
def add_user(un, pw):
    user = UserEntry( username=un, saltedPwd=make_pw_hash(un, pw) )
    user.put()

def available_username(username):
    if( get_user_entry(username) == None):
        return True

def get_user_entry(username):
    user = db.GqlQuery("SELECT * FROM UserEntry WHERE username = :1", username)
    user.get()
    if( user.count(1) != 0 ):
        return user.get()

def login_success(username, pwd):
    # get user entry
    db_user = get_user_entry(username)
    # compare salted hash of input to stored
    return valid_pw(username, pwd, db_user.saltedPwd)
    
#
# Password Handling
#
def make_salt():
    return ''.join(random.choice(string.letters) for x in xrange(5))

def make_pw_hash(name, pw, salt=None):
    if not salt:
        salt=make_salt()
    h = hashlib.sha256(name + pw + salt).hexdigest()
    return '%s,%s' % (h, salt)

def valid_pw(name, pw, h):
    salt = h.split(',')[1]
    return h == make_pw_hash(name, pw, salt)

